import {
  ModalForm,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { Button, Upload } from 'antd';
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import useStyles from '../style.style';
import { getProjectDetail } from '../service';
import { useRequest } from '@umijs/max';

type OperationModalProps = {
  open: boolean;
  current: any;
  onCancel: () => void;
  onSubmit: (values: any, id?: number | string) => void;
  children?: React.ReactNode;
};
const OperationModal: FC<OperationModalProps> = (props) => {
  const { styles } = useStyles();
  const { open, current, onCancel, onSubmit, children } = props;
  const [newFileList, setNewFileList] = useState<any[]>([]);
  const [projectDetail, setProjectDetail] = useState<any>(null);

  // 获取项目详情
  const { run: fetchProjectDetail, loading: detailLoading } = useRequest(
    getProjectDetail,
    {
      manual: true,
      onSuccess: (result) => {
        setProjectDetail(result);
        // 如果有文件，设置到文件列表中
        if (result?.script_files && result.script_files.length > 0) {
          const fileList = result.script_files.map((file: any, index: number) => ({
            uid: `existing-${index}`,
            name: file.name || file.filename || `文件${index + 1}`,
            status: 'done',
            url: file.url || file.path,
            response: file,
          }));
          setNewFileList(fileList);
        }
      },
    }
  );

  useEffect(() => {
    if (open) {
      if (current?.id) {
        // 编辑模式：获取项目详情
        fetchProjectDetail(current.id);
      } else {
        // 新增模式：重置文件列表
        setNewFileList([]);
        setProjectDetail(null);
      }
    }
  }, [open, current?.id])

  const handleNewFileChange: UploadProps['onChange'] = (info) => {
    let updatedFileList = [...info.fileList];

    // 1. Limit the number of uploaded files
    updatedFileList = updatedFileList.slice(-1);

    setNewFileList(updatedFileList);
  };

  const uploadProps = {
    onChange: handleNewFileChange,
    maxCount: 1,
    beforeUpload: () => false, // 阻止自动上传
    onRemove: (file: any) => {
      // 允许删除文件
      return true;
    },
  };

  if (!open) {
    return null;
  }

  return (
    <ModalForm
      open={open}
      title={`${current ? '编辑' : '新增'}项目`}
      className={styles.standardListForm}
      width={640}
      onFinish={async (values) => {
        const params = {
          ...values,
          project_id: current?.id,
          script_files: current ? newFileList : newFileList // 编辑和新增都传递文件列表
        }
        onSubmit(params);
      }}
      initialValues={current?.id ? projectDetail : current}
      submitter={{
        render: (_, dom) => dom,
      }}
      trigger={children}
      modalProps={{
        onCancel: () => onCancel(),
        destroyOnClose: true,
        bodyStyle: {
          padding: '72px 0',
        },
      }}
    >
      <ProFormText
        name="title"
        label="项目名称"
        rules={[
          {
            required: true,
            message: '请输入项目名称',
          },
        ]}
        placeholder="请输入"
      />
      <ProFormTextArea
        name="description"
        label="项目描述"
        rules={[
          {
            message: '请输入项目描述！',
          },
        ]}
        placeholder="请输入"
      />
      <div className={styles.uploadWrap}>
        <div>剧本上传</div>
        <Upload {...uploadProps} fileList={newFileList}>
          <Button icon={<UploadOutlined />}>Upload </Button>
        </Upload>
      </div>
    </ModalForm>
  );
};
export default OperationModal;
